import { EntityManager, MikroORM, knex } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Body, Controller, Get, Post, Query, Req } from '@nestjs/common';
import { Users } from '@databases/entities/Users';
import { ApiOperation } from '@nestjs/swagger';
import { UserskVO } from '@databases/vo/UserVO';
import { knexPrefix, prefix } from '@databases/vo/dao-helper';
import { JsonApiResponse } from '@utils/json.api.response';
import { knext } from 'knext';
 
@Controller('user')
export class UserController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager
    ){}

    @ApiOperation({summary:'获取所有用户'})
    @Get('list')
    async list(@Query('keyword') keyword) {
        const knex = knext(this)
        const users = await knex
        .fromORM(Users,'users')
        .select(
            ...knexPrefix(UserskVO.baseInfo())
        )
        .whereILike({name:'%keyword%'})
        .orWhereLike({id_number:'%keyword%'})
        .orWhereLike({phone_number:'%keyword%'})
        .limit(10)
        .populate()
         
        return JsonApiResponse.new(users)
    }

    @Post('set_roles')
    async setRole(
        @Req() request,
        @Body('user_id') user_id,
        @Body('roles') roles
    ){
        let knex = knext(this)
        let res = await knex.fromORM(Users)
        .update({roles:JSON.stringify(roles)})
        .where({id:user_id})

        return JsonApiResponse.object(roles)
    }

    @Post('set_modules')
    async setModules(
        @Req() request,
        @Body('user_id') user_id,
        @Body('modules') modules
    ){
        let knex = knext(this)
        let res = await knex.fromORM(Users)
        .update({modules:JSON.stringify(modules)})
        .where({id:user_id})

        return JsonApiResponse.object(modules)
    }

    @Get('info')
    async info(
        @Req() request,
        @Query('user_id') user_id
    ){
        let knex = knext(this)
        let res = await knex.fromORM(Users)
        .select(knexPrefix(UserskVO.baseInfo()))
        .where({'id': user_id})
        .getOne()

        return JsonApiResponse.object(res)
    }
}
